<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv  是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false) {
    $type = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }

            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/*
 * 获取客户端浏览器
 */

function getagent() {
    if (false !== strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 8.0"))
        return "IE 8.0";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 7.0"))
        return "IE 7.0";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 6.0"))
        return "IE 6.0";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "Firefox/3"))
        return "Firefox 3";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "Firefox/2"))
        return "Firefox 2";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "Chrome"))
        return "Google Chrome";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "Safari"))
        return "Safari";
    elseif (false !== strpos($_SERVER["HTTP_USER_AGENT"], "Opera"))
        return "Opera";
    else
        return $_SERVER["HTTP_USER_AGENT"];
}

/*
 * 获取客户端的os
 */

function os_infor() {
    $os = "";
    $Agent = $_SERVER["HTTP_USER_AGENT"];

    if (preg_match('/win/i', $Agent) && strpos($Agent, '95')) {
        $os = "Windows 95";
    } elseif (preg_match('/win 9x/i', $Agent) && strpos($Agent, '4.90')) {
        $os = "Windows ME";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/98/i', $Agent)) {
        $os = "Windows 98";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/nt 5.0/i', $Agent)) {
        $os = "Windows 2000";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/nt 5.1/i', $Agent)) {
        $os = "Windows XP";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/nt 6.0/i', $Agent)) {
        $os = "Windows Vista";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/nt 6.1/i', $Agent)) {
        $os = "Windows 7";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/nt/i', $Agent)) {
        $os = "Windows NT";
    } elseif (preg_match('/win/i', $Agent) && preg_match('/32/i', $Agent)) {
        $os = "Windows 32";
    } elseif (preg_match('/linux/i', $Agent)) {
        $os = "Linux";
    } elseif (preg_match('/unix/i', $Agent)) {
        $os = "Unix";
    } elseif (preg_match('/sun/i', $Agent) && preg_match('/os/i', $Agent)) {
        $os = "SunOS";
    } elseif (preg_match('/ibm/i', $Agent) && preg_match('/os/i', $Agent)) {
        $os = "IBM OS/2";
    } elseif (preg_match('/Mac/i', $Agent) && preg_match('/PC/i', $Agent)) {
        $os = "Macintosh";
    } elseif (preg_match('/PowerPC/i', $Agent)) {
        $os = "PowerPC";
    } elseif (preg_match('/AIX/i', $Agent)) {
        $os = "AIX";
    } elseif (preg_match('/HPUX/i', $Agent)) {
        $os = "HPUX";
    } elseif (preg_match('/NetBSD/i', $Agent)) {
        $os = "NetBSD";
    } elseif (preg_match('/BSD/i', $Agent)) {
        $os = "BSD";
    } elseif (preg_match('/OSF1/i', $Agent)) {
        $os = "OSF1";
    } elseif (preg_match('/IRIX/i', $Agent)) {
        $os = "IRIX";
    } elseif (preg_match('/FreeBSD/i', $Agent)) {
        $os = "FreeBSD";
    }
    if ($os == '')
        $os = "Unknown";
    return $os;
}

/*
 * 获取客户端语言
 */

function getlanguage() {
    //只取前4位，这样只判断最优先的语言。如果取前5位，可能出现en,zh的情况，影响判断。
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4);
    if (preg_match("/zh-c/i", $lang))
        return "简体中文";
    else if (preg_match("/zh/i", $lang))
        return "正体中文";
    else if (preg_match("/en/i", $lang))
        return "English";
    else if (preg_match("/fr/i", $lang))
        return "French";
    else if (preg_match("/de/i", $lang))
        return "German";
    else if (preg_match("/jp/i", $lang))
        return "Japanese";
    else if (preg_match("/ko/i", $lang))
        return "Korean";
    else if (preg_match("/es/i", $lang))
        return "Spanish";
    else if (preg_match("/sv/i", $lang))
        return "Swedish";
    else
        return "unknown Lanage";
}


function curl_get(string $url) {
    $headers = array(
        'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding:gzip, deflate, sdch',
        'Accept-Language:zh-CN,zh;q=0.8',
        'Cache-Control:max-age=0',
        'Connection:keep-alive'
    );

    $ch = curl_init();
    //curl_setopt($ch, CURLOPT_HEADER, $headers);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:111.222.333.4', 'CLIENT-IP:111.222.333.4'));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function curl_get2(string $url) {


    $ch = curl_init();
    //curl_setopt($ch, CURLOPT_HEADER, $headers);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:111.222.333.4', 'CLIENT-IP:111.222.333.4'));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function curl_get3(string $url) {


    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 1);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);

    return $data;
}

function curl_post($url, $post_data) {
    $curl = curl_init();
//设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 1);
//设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
//设置post数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
//执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
//显示获得的数据
    return $data;
}

function getCon(string $html, string $select, bool $node = false) {
    $document = new \DOMDocument();
    @$document->loadHTML($html);
    //$content = mb_convert_encoding($data, 'UTF-8', 'gbk');
    $xpath = new \DOMXPath($document);
    //默认选择要查找的id
    $elements = $xpath->query($select);
    //var_dump($elements);
    $con = '';
    if ($elements->length != 0) {
        //$this->dump($elements[0]);exit;
        $con = $document->saveHTML($elements[0]);
        if ($node) {
            $con = $elements[0]->nodeValue;
        } else {
            $con = $document->saveHTML($elements[0]); //本身带标签
        }
    }
    return $con;
}

function getContent(string $html, string $select, $node = false, bool $ischeck = false) {
    $document = new \DOMDocument();
    @$document->loadHTML($html);
    //$content = mb_convert_encoding($data, 'UTF-8', 'gbk');
    $xpath = new \DOMXPath($document);
    //默认选择要查找的id
    $elements = $xpath->query($select);
    //dump($elements);exit;
    $con = '';
    if ($elements->length === 1) {
        if ($node) {
            $con = $elements[0]->nodeValue;
        } else {
            $con = $document->saveHTML($elements[0]);
        }
        if ($ischeck) {
            $check = mb_detect_encoding($con, array('UTF-8', 'GB2312', 'GBK', 'GB18030', 'ISO-8859-1', 'ASCII'));
            //return $check;
            if ($check == 'UTF-8') {
                return $con;
            } elseif ($check == 'cp936') {
                return mb_convert_encoding($con, 'UTF-8', 'cp936');
            } else {
                $check;
            }
            //$con = mb_convert_encoding($con, 'UTF-8', 'cp936');
        }

    } else if ($elements->length > 1) {
        $con = [];
        foreach ($elements as $k => $v) {
            if ($node) {
                $con[$k] = $elements[$k]->nodeValue;
            } else {
                $con[$k] = $document->saveHTML($elements[$k]);
            }
        }
    }

    return $con;
}

/** 用xpath从html中获取数据
 * @param string $html
 * @param array  $fields
 * @param bool   $ischeck
 * @return array|null
 */
function getConFromHtml(string $html, array $fields = [], bool $ischeck = false) {
    $return = [];
    $document = new \DOMDocument();
    @$document->loadHTML($html);
    $xpath = new \DOMXPath($document);
    if (!empty($fields) && is_array($fields)) {

        foreach ($fields as $name => $select) {
            $elements[$name] = $xpath->query($select['select']);
            if ($elements[$name]->length != 0) {
                foreach ($elements[$name] as $k => $v) {
                    if ($select['node'] === true) {
                        $return[$k][$name] = $v->nodeValue;
                    } else {
                        $return[$k][$name] = $document->saveHTML($v);
                    }
                }
            }
        }
    }

    return $return;
}

/** 根据zwdu表id选择内容表
 * @param $id
 * @return string
 */
function switchTableById($id) {
    if ($id <= 2000) {
        return 'con_0';
    } else if ($id > 2000 && $id <= 4000) {
        return 'con_2000';
    } else if ($id > 4000 && $id <= 6000) {
        return 'con_4000';
    } else if ($id > 6000 && $id <= 8000) {
        return 'con_6000';
    } else if ($id > 8000 && $id <= 10000) {
        return 'con_8000';
    } else if ($id > 10000 && $id <= 12000) {
        return 'con_10000';
    } else if ($id > 12000 && $id <= 14000) {
        return 'con_12000';
    } else if ($id > 14000 && $id <= 16000) {
        return 'con_14000';
    } else if ($id > 16000 && $id <= 18000) {
        return 'con_16000';
    } else if ($id > 18000 && $id <= 20000) {
        return 'con_18000';
    } else if ($id > 20000 && $id <= 22000) {
        return 'con_20000';
    } else if ($id > 22000 && $id <= 24000) {
        return 'con_22000';
    } else if ($id > 24000 && $id <= 26000) {
        return 'con_24000';
    } else if ($id > 26000 && $id <= 28000) {
        return 'con_26000';
    } else if ($id > 28000 && $id <= 30000) {
        return 'con_28000';
    } else if ($id > 30000 && $id <= 32000) {
        return 'con_30000';
    } else if ($id > 32000 && $id <= 34000) {
        return 'con_32000';
    } else if ($id > 34000 && $id <= 36000) {
        return 'con_34000';
    } else if ($id > 36000 && $id <= 38000) {
        return 'con_36000';
    }
}

function switchTableById2($id) {
    switch ($id) {
        case $id <= 2000:
            return 'con_0';
            break;
        case $id > 2000 && $id <= 4000:
            return 'con_2000';
            break;
        case $id > 4000 && $id <= 6000:
            return 'con_4000';
            break;
        case $id > 6000 && $id <= 8000:
            return 'con_6000';
            break;
        case $id > 8000 && $id <= 10000:
            return 'con_8000';
            break;
        case $id > 10000 && $id <= 12000:
            return 'con_10000';
            break;
        case $id > 12000 && $id <= 14000:
            return 'con_12000';
            break;
        case $id > 14000 && $id <= 16000:
            return 'con_14000';
            break;
        case $id > 16000 && $id <= 18000:
            return 'con_16000';
            break;
        case $id > 18000 && $id <= 20000:
            return 'con_18000';
            break;
        case $id > 20000 && $id <= 22000:
            return 'con_20000';
            break;
        case $id > 22000 && $id <= 24000:
            return 'con_22000';
            break;
        case $id > 24000 && $id <= 26000:
            return 'con_24000';
            break;
        case $id > 26000 && $id <= 28000:
            return 'con_26000';
            break;
        case $id > 28000 && $id <= 30000:
            return 'con_28000';
            break;
        case $id > 30000 && $id <= 32000:
            return 'con_30000';
            break;
        case $id > 32000 && $id <= 34000:
            return 'con_32000';
            break;
        case $id > 34000 && $id <= 36000:
            return 'con_34000';
            break;
        case $id > 36000 && $id <= 38000:
            return 'con_36000';
            break;
        case $id > 38000 && $id <= 40000:
            return 'con_38000';
            break;
        case $id > 40000 && $id <= 42000:
            return 'con_40000';
            break;
        case $id > 42000 && $id <= 44000:
            return 'con_42000';
            break;
    }

}

function baidu_curl($urls) {
    $api = 'http://data.zz.baidu.com/urls?site=www.xiaojuan.fun&token=O6mADHhmR90Pj25I';
    $ch = curl_init();
    $options = array(
        CURLOPT_URL            => $api,
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => implode("\n", $urls),
        CURLOPT_HTTPHEADER     => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    return curl_exec($ch);
}

function getfield(string $html, string $select, $node = false) {
    $return = '';
    $document = new \DOMDocument();
    @$document->loadHTML($html);
    $xpath = new \DOMXPath($document);
    if (!empty($select)) {
        $elements = $xpath->query($select);
        if ($elements->length != 0) {
            if ($node) {
                $return = $elements[0]->nodeValue;
            } else {
                $return = $document->saveHTML($elements[0]); //本身带标签
            }
        }
        return $return;
    }
}

function getConFromHtml3(string $html, array $fields = []) {
    $document = new \DOMDocument();
    @$document->loadHTML($html);
    $xpath = new \DOMXPath($document);
    $r = [];
    if (!empty($fields)) {
        foreach ($fields as $fields_k => $fields_v) {
            $elements_s[$fields_k] = $xpath->query($fields_v['select']);

            if ($elements_s[$fields_k]->length != 0) {
                for ($i = 0; $i < $elements_s[$fields_k]->length; $i++) {
                    $title = $elements_s[$fields_k][$i]->nodeValue;
                    $url = $elements_s[$fields_k][$i]->attributes[0]->nodeValue;

                    $r[] = ['title' => $title, 'url' => $url];
                }

            }
        }
    }
    return $r;

}


